package cn.com.dbappsecurity.frame.paramparse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import cn.com.dbappsecurity.frame.annotations.Validate;
import cn.com.dbappsecurity.frame.exception.FrameException;
import cn.com.dbappsecurity.frame.request.MultipartRequest;

public class ParamFile implements IParamParse {

	private String name;
	private Validate validate;
	private boolean array;
	
	public ParamFile(String name,boolean array,Validate validate){
		this.name = name;
		this.array = array;
		this.validate = validate;
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MultipartRequest mpReq = (MultipartRequest)request;
		FileItem[] value = mpReq.getFiles(name);
		if(!validate(value)){
			throw new FrameException(FrameException.TYPE_ARGU_ERROR);
		}
		return array ? value : (value.length == 0 ? null : value[0]);
	}
	
	private boolean validate(FileItem[] value) {
		if(validate != null){
			if(validate.required() && value.length == 0){
				return false;
			}
			for(FileItem val : value){
				if(validate.required() && val == null){
					return false;
				}
				double minLen = validate.minLen();
				if(minLen != -1){
					if(val.getSize() < minLen){
						return false;
					}
				}
				double maxLen = validate.maxLen();
				if(maxLen != -1){
					if(val.getSize() > maxLen){
						return false;
					}
				}
				String[] types = validate.allowType();
				if(types.length > 0){
					String name = val.getName().toLowerCase();
					boolean allow = false;
					for(String type : types){
						if(name.endsWith("."+type.toLowerCase())){
							allow = true;
							break;
						}
					}
					if(!allow){
						return false;
					}
				}
			}
		}
		return true;
	}
	
}
